# from django.shortcuts import render
#
# # Create your views here.

from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from .models import User
from django.http import JsonResponse, HttpResponseForbidden
from utils.response_code import RETCODE


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        #接受请求参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        if allow != 'on':
            return HttpResponseForbidden("请勾选用户协议")
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg':'注册失败'})
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=3600*24*14)
        return response


# class UsernameCountView(View):
#     """判断用户名是否重复注册"""
#     def get(self, request, username):
#         count = User.objects.filter(username=username).count()
#         return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})
class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

class MoblieCounView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})



